<script setup>
import { ref, onMounted, computed } from 'vue'
import { onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import ToSearch from '@/components/ToSearch.vue'
import DishItem from '@/components/DishItem.vue'
import { getRandomDishAPI, getRandomDishLoginAPI } from '@/api/home'
import { useUserStore } from '@/stores'

const userStore = useUserStore()

// 菜品列表数据
const dishList = ref([])
const loading = ref(false)
const finished = ref(false)
const currentPage = ref(1)
const pageSize = ref(5)

// 计算统计数据
const dishStats = computed(() => {
  if (dishList.value.length === 0) {
    return {
      totalCount: 0,
      averageRating: 0,
      totalRatings: 0
    }
  }

  const total = dishList.value.length
  const totalRatingSum = dishList.value.reduce((sum, dish) => sum + (dish.dishRating || 0), 0)
  const averageRating = (totalRatingSum / total).toFixed(1)
  const totalRatingCount = dishList.value.reduce((sum, dish) => sum + (dish.ratingCount || 0), 0)
  const formattedRatingCount = totalRatingCount > 10 ? `${Math.floor(totalRatingCount / 10) * 10}+` : totalRatingCount.toString()

  return {
    totalCount: total,
    averageRating: parseFloat(averageRating),
    totalRatings: formattedRatingCount
  }
})

// 导航项数据
const navItems = [
  { icon: 'paixing', text: '排行', path: '/pages/Ranking/index' },
  { icon: 'reliang', text: '热量对比', path: '/pages/HeatVS/index' },
  { icon: 'doubao', text: 'AI计划', path: '无' }
]

// 导航项点击事件
const handleNavClick = (item) => {
  if(item.text==='AI计划'){
    uni.showToast({
      title: 'AI计划功能正在开发中，敬请期待！',
      icon: 'none'
    })
    return
  }
  uni.navigateTo({
    url: item.path
  })
}

// 加载菜品数据
const loadDishes = async (isRefresh = false) => {
  if (loading.value || finished.value) return

  loading.value = true
  
    try {
      let res
      if (userStore.isLoggedIn) {
        const userId = userStore.userInfo?.id || '1'
        res = await getRandomDishLoginAPI(userId, currentPage.value, pageSize.value, isRefresh)
      } else {
        res = await getRandomDishAPI(currentPage.value, pageSize.value)
      }
    
    if (res.code === 1 && res.data) {
      const newDishes = res.data.records || res.data.list || res.data || []
      
      if (isRefresh) {
        // 刷新时替换数据
        dishList.value = newDishes
      } else {
        // 加载更多时追加数据
        dishList.value.push(...newDishes)
      }
      
      // 检查是否已经没有更多数据
      if (newDishes.length < pageSize.value) {
        finished.value = true
      } else {
        currentPage.value++
      }
    } else {
      uni.showToast({
        title: res.message || res.msg || '加载失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('加载菜品失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 下拉刷新
const handleRefresh = async () => {
  currentPage.value = 1
  finished.value = false
  await loadDishes(true)
  uni.stopPullDownRefresh()
}

// 页面加载时初始化数据
onMounted(async () => {
  loadDishes(true)
})

// 触底加载更多
onReachBottom(() => {
  if (!finished.value && !loading.value) {
    loadDishes()
  }
})

// 下拉刷新
onPullDownRefresh(() => {
  handleRefresh()
})
</script>

<template>
  <view class="home-container">
    <!-- 搜索框 -->
    <ToSearch />

    <!-- 分割线 -->
    <view class="divider"></view>

    <!-- 导航栏 -->
    <view class="home-nav-container">
      <view
        v-for="item in navItems"
        :key="item.text"
        class="nav-item"
        @tap="handleNavClick(item)"
      >
        <view class="icon-container">
          <text :class="'iconfont icon-' + item.icon"></text>
        </view>
        <text class="nav-text">{{ item.text }}</text>
      </view>
    </view>

    <!-- 分割线 -->
    <view class="divider"></view>

    <!-- 菜品列表标题 -->
    <view class="dish-section-title">
      <view class="title-header">
        <text class="title-main">
          <text class="iconfont icon-caipin"></text>
          推荐菜品
        </text>
        <view class="title-badge">
          <text class="iconfont icon-jingxuan"></text>
          <text>热门</text>
        </view>
      </view>
      <text class="title-subtitle">为你精选美味菜品</text>
      <view class="stats-row">
        <view class="stat-item">
          <text class="stat-number">{{ dishStats.totalCount }}</text>
          <text class="stat-label">已推荐</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item">
          <text class="stat-number">{{ dishStats.totalRatings }}</text>
          <text class="stat-label">用户评分</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item">
          <text class="stat-number">{{ dishStats.averageRating }}</text>
          <text class="stat-label">平均评分</text>
        </view>
      </view>
    </view>

    <!-- 无限加载菜品列表 -->
    <view class="dish-list-container">
      <view
        v-for="dish in dishList"
        :key="dish.id"
        class="dish-item-wrapper"
      >
        <DishItem :dish="dish" />
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>

      <!-- 加载完成提示 -->
      <view v-if="finished && !loading" class="finished-container">
        <text>🎉 已经到底了~</text>
      </view>

      <!-- 下拉加载提示 -->
      <view
        v-if="!finished && !loading && dishList.length > 0"
        class="scroll-tip-container"
      >
        <text>👇 下拉加载更多</text>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.home-container {
  min-height: 92vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 30rpx 48rpx calc(20rpx + env(safe-area-inset-bottom)) 48rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

// 分割线
.divider {
  width: 100%;
  max-width: 600rpx;
  height: 2rpx;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(102, 126, 234, 0.3),
    transparent
  );
  margin: 24rpx 0;
}

// 导航栏
.home-nav-container {
  width: 100%;
  max-width: 600rpx;
  display: flex;
  justify-content: space-between;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(40rpx);
  border-radius: 30rpx;
  padding: 30rpx 20rpx;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.1);
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  margin-bottom: 10rpx;

  .nav-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    transition: all 0.3s ease;
    padding: 16rpx 8rpx;
    border-radius: 24rpx;
    flex: 1;
    max-width: 25%;

    &:active {
      background: rgba(102, 126, 234, 0.05);
      transform: translateY(-2rpx);

      .icon-container {
        transform: scale(1.05);
        background: linear-gradient(45deg, #667eea, #764ba2);

        .iconfont {
          color: white;
        }
      }

      .nav-text {
        color: #667eea;
        font-weight: 600;
      }
    }

    .icon-container {
      width: 70rpx;
      height: 70rpx;
      background: rgba(102, 126, 234, 0.1);
      border-radius: 24rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 12rpx;
      transition: all 0.3s ease;

      .iconfont {
        font-size: 36rpx;
        color: #667eea;
        transition: color 0.3s ease;
      }
    }

    .nav-text {
      font-size: 22rpx;
      color: #666;
      font-weight: 500;
      transition: all 0.3s ease;
      text-align: center;
      line-height: 1.2;
    }
  }
}

// 菜品区域标题
.dish-section-title {
  width: 100%;
  max-width: 580rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(40rpx);
  border-radius: 40rpx;
  padding: 48rpx 40rpx;
  margin: 16rpx 0 48rpx 0;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.1);
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 6rpx;
    background: linear-gradient(90deg, #667eea, #764ba2, #f093fb, #f5576c);
    background-size: 200% 100%;
    animation: gradientShift 3s ease-in-out infinite;
  }

  .title-header {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 24rpx;
    margin-bottom: 16rpx;

    .title-main {
      font-size: 40rpx;
      font-weight: 600;
      color: #333;
      display: flex;
      align-items: center;

      .iconfont {
        font-size: 44rpx;
        color: #667eea;
        margin-right: 16rpx;
      }
    }

    .title-badge {
      background: linear-gradient(45deg, #ff6b6b, #ff8e8e);
      color: white;
      padding: 8rpx 24rpx;
      border-radius: 24rpx;
      font-size: 24rpx;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 8rpx;
      box-shadow: 0 4rpx 16rpx rgba(255, 107, 107, 0.3);

      .iconfont {
        font-size: 24rpx;
      }
    }
  }

  .title-subtitle {
    font-size: 28rpx;
    color: #999;
    margin: 0 0 32rpx 0;
    opacity: 0.8;
    text-align: center;
    display: block;
  }

  .stats-row {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 32rpx;

    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8rpx;

      .stat-number {
        font-size: 36rpx;
        font-weight: 700;
        color: #667eea;
        line-height: 1;
      }

      .stat-label {
        font-size: 22rpx;
        color: #999;
        opacity: 0.8;
      }
    }

    .stat-divider {
      width: 2rpx;
      height: 48rpx;
      background: linear-gradient(
        to bottom,
        transparent,
        rgba(102, 126, 234, 0.3),
        transparent
      );
    }
  }
}

// 菜品列表容器
.dish-list-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 32rpx;

  .dish-item-wrapper {
    width: 100%;
    animation: fadeInUp 0.6s ease forwards;
  }

  // 加载状态
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 80rpx 40rpx;
    color: #666;

    .loading-spinner {
      width: 64rpx;
      height: 64rpx;
      border: 6rpx solid rgba(102, 126, 234, 0.2);
      border-top: 6rpx solid #667eea;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 32rpx;
    }

    text {
      font-size: 28rpx;
      opacity: 0.8;
    }
  }

  // 加载完成提示
  .finished-container {
    text-align: center;
    padding: 80rpx 40rpx;
    color: #999;

    text {
      font-size: 28rpx;
      opacity: 0.8;
    }
  }

  // 下拉加载提示
  .scroll-tip-container {
    text-align: center;
    padding: 60rpx 40rpx;
    color: #999;

    text {
      font-size: 26rpx;
      opacity: 0.6;
      animation: bounce 2s infinite;
    }
  }
}

// 动画
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(60rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes bounce {
  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-20rpx);
  }
  60% {
    transform: translateY(-10rpx);
  }
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}
</style>